/**
 * Created by zhulizhe on 2017/8/16.
 */
import React, {Component} from 'react';
import {
    Text,
    View,
    TouchableOpacity,
    Image,
    Dimensions,
    StyleSheet,
    ScrollView,
    Animated,
    RefreshControl,
    DeviceEventEmitter,
    InteractionManager
} from 'react-native';

import ViewPager from '../component/ViewPager'
import Ionicons from 'react-native-vector-icons/Ionicons';
import SplashScreen from 'react-native-splash-screen'
import * as WeChat from 'react-native-wechat'
import Constant from "../Contant";
import {observer} from "mobx-react";
import {observable} from 'mobx'
import WaterTiketShowModal from '../component/WaterTiketShowModal'
import Placeholder from 'rn-placeholder';
const screenWidth = Dimensions.get('window').width;
import LinearGradient from "react-native-linear-gradient";
import addressMgrStore from '../store/AddrMgrStore'
import {observe} from "../../node_modules/mobx/lib/mobx";
import RequestUtil from '../util/NetUtil'
import Resolution from '../util/Resolution'


// 头部背景组件
export const Bg = ({height = 132}) => {
    return <View style={{height: height, left: 0, width: '100%', top: 0, position: 'absolute'}}>
        <LinearGradient colors={['#14c2fc', '#399cfc']} style={{flex: 1}}/>
    </View>
}

// 顶部 搜索组件
const Header = observer(({onClick}) => {
    let address = addressMgrStore.activeAddress;
    return <View
        style={{paddingHorizontal: 15, paddingTop: 30, paddingBottom: 10}}>
        <TouchableOpacity
            onPress={onClick}
            activeOpacity={0.9}
            style={{
                justifyContent: 'space-between',
                alignItems: 'center',
                flexDirection: 'row',
                backgroundColor: '#00000000'
            }}>
            <View style={{
                alignItems: 'center',
                flexDirection: 'row',
                paddingVertical: 15,
                height:40,
                flex:1
            }}>
                <Image source={require('../../asserts/home/Location-Icon.png')}/>
                <Text style={{
                    textAlign: 'left',
                    paddingHorizontal: 10,
                    fontSize: 18,
                    color: '#fff',
                    fontWeight: '500',
                    maxWidth: '90%',
                }} numberOfLines={1}>{address.mappingAddress}</Text>
                <Image source={require('../../asserts/home/Drop-triangle.png')}/>
            </View>
            <View>
                {/*<Ionicons name="ios-cart-outline" color="#fff" size={20}/>*/}
            </View>
        </TouchableOpacity>
        <View style={{
            marginHorizontal: 5,
            backgroundColor: '#fff',
            height: 30,
            alignItems: 'center',
            justifyContent: 'center'
        }}>
            <TouchableOpacity style={{flexDirection: 'row', alignItems: 'center'}}>
                <View style={{paddingHorizontal: 5}}>
                    <Image style={{width: '100%'}} source={require('../../asserts/home/Magnifier.png')}/>
                </View>
                <Text style={{color: Constant.TEXT_COLOR_6, fontSize: 13}}>输入商家，商品名称</Text>
            </TouchableOpacity>
        </View>
    </View>
})

// 上次订水组件
const LastAddress = ({onClick}) => {
    return <TouchableOpacity
        activeOpacity={1}
        onPress={onClick}
        style={{
            justifyContent: 'space-between',
            flexDirection: 'row',
            paddingHorizontal: 10,
            backgroundColor: '#fff',
            paddingVertical: 15,
            marginBottom: 5
        }}>
        <View style={{flexDirection: 'row', alignItems: 'center'}}>
            <View>
                <Image source={require('../../asserts/home/time-icon.png')}/>
            </View>
            <View style={{paddingHorizontal: 5}}>
                <Text style={{color: 'gray', fontSize: 13}}>您上次订购过的水站:</Text>
            </View>
            <View>
                <Text style={{color: Constant.BLUECOLOR, fontSize: 14}}>乐百氏旗舰店</Text>
            </View>
        </View>
        <View>
            <Ionicons name="ios-arrow-forward-outline" size={14} color={Constant.BLUECOLOR}/>
        </View>
    </TouchableOpacity>
}

// 通用标签组件
const Label = ({title}) => {
    return <View style={{padding: 12.5}}>
        <Text style={{
            color: Constant.TEXT_COLOR_3,
            fontSize: Constant.FONT_SIZE_32,
            fontWeight: '500'
        }}>{title}</Text>
    </View>
}

// 喜腾山泉推广banner
const Banner = () => {
    const img = require('../../asserts/home/banner1.png');
    return <ViewPager images={[img]}/>
}

// 互联网合作品牌
const InternetBrand = ({list = []}) => {
    if (list.length == 0) return null;
    const Item = ({brand,index}) => {
        let imageSource = {uri: brand.imageUrl};
        if (brand.imageUrl == null) {
            imageSource = require('../../asserts/home_nav_bg.png')
        }
        return <View style={{
            backgroundColor: '#fff',
            paddingTop: 10
        }}>
            <Image
                resizeMode='contain'
                style={{
                    width: '100%' - 20,
                    height: Resolution.px2dp(54),
                    marginHorizontal: 10,
                    borderColor: Constant.COLOR_E5,
                    borderWidth: StyleSheet.hairlineWidth,
                }} source={imageSource}/>
        </View>
    }

    return <View>
        <Label title="互联网合作品牌"/>
        {
            list.map((brand, index) => {
                return <Item
                    key={index}
                    brand={brand}/>
            })
        }
    </View>
}

const padding = 10;
const column = 4;
const BrandImageWidth = (screenWidth - (column + 1) * padding) / column;
const BrandImageHeight = 50;

const BannerCell = observer(({data}) => {
    let imageSource = {uri: data.imageUrl};
    if (data.imageUrl == null) {
        imageSource = require('../../asserts/home_nav_bg.png')
    }

    return <View>
        <Image resizeMode='stretch' style={{width: BrandImageWidth, height: BrandImageHeight}}
               source={imageSource}/>
    </View>
})

// 热卖品牌
const HotSalesBrand = observer(({onClick, list = []}) => {
    if (list.length == 0) return null;

    return <View>
        <Label title="热销品牌"/>
        <View style={{flexWrap: 'wrap', flexDirection: 'row', marginLeft: 5, backgroundColor: '#fff'}}>
            {
                list.map((data, index) => {
                    return <View
                        key={index}
                        style={{
                            marginHorizontal: 5,
                            marginBottom: 5
                        }}>
                        <TouchableOpacity
                            onPress={onClick}>
                            <BannerCell data={data}/>
                        </TouchableOpacity>
                    </View>
                })
            }
        </View>
    </View>
})

// 本地品牌
const LocalBrand = observer(({list = []}) => {
    if (list.length == 0) return null;
    return <View>
        <Label title="本地特色"/>
        <View style={{flexWrap: 'wrap', flexDirection: 'row', marginLeft: 5, backgroundColor: '#fff'}}>
            {
                list.map((data, index) => {
                    return <View
                        key={index}
                        style={{marginHorizontal: 5, marginBottom: index == list.length - 1 ? 0 : 5}}>
                        <BannerCell data={data}/>
                    </View>
                })
            }
        </View>
    </View>
})
class StarItem {
    constructor(index, imageSource) {
        this.index = index;
        this.imageSource = imageSource;
    }
}

// 评级组件
export const Star = ({count = 5, max = 5, onChange, size = 12, subfix = '分'}) => {
    const currentCount = observable(count);
    let isOdd = count % 2 == 0 ? false : true;
    const StarCom = observer(() => {
        let stars = [];
        const addStar = (imageSource) => {
            let index = stars.length;
            stars.push(new StarItem(index, imageSource));
        }

        if (onChange) {
            for (let i = 0; i < currentCount * 1; i++) {
                addStar(require('../../luoasserts/me/icon_star_orange.png'));
            }
        }
        else {
            // step one
            for (let i = 0; i < (currentCount * 1 - 1) / 2; i++) {
                addStar(require('../../luoasserts/me/icon_star_orange.png'));
            }

            if (isOdd) {
                addStar(require('../../asserts/shop/icon_star_half.png'));
            }
        }

        let unselectedCount = max - stars.length;
        for (let i = 0; i < unselectedCount; i++) {
            addStar(require('../../luoasserts/me/icon_star_gray.png'));
        }

        return <View style={{flexDirection: 'row', alignItems: 'center'}}>
            {
                stars.map(item => {
                    return <TouchableOpacity
                        key={item.index}
                        activeOpacity={0.9}
                        onPress={() => {
                            if (onChange) {
                                currentCount.set(item.index + 1);
                                onChange(item.index+1);
                            }
                        }}
                        style={{padding: 2}}>
                        <Image
                            style={{width: size, height: size}}
                            source={item.imageSource}/>
                    </TouchableOpacity>
                })
            }
            <View style={{flexDirection: 'row', alignItems: 'center'}}>
                <Text style={{color: Constant.TEXT_COLOR_6}}>{onChange?2*(currentCount * 1)+'' : currentCount * 1+'' }</Text>
                <Text style={{color: Constant.TEXT_COLOR_6}}>{subfix}</Text>
            </View>
        </View>
    })
    return <StarCom/>
}


// 附近店铺
const ShopCell = ({shop, onClick}) => {
    let {shopId, score, saleMount, imageUrl, name, address, distance, deliveryTime, totalProductCount, shareUrl} = shop;

    return <TouchableOpacity
        activeOpacity={0.9}
        onPress={onClick}
        style={[{
            justifyContent: 'space-between',
            flexDirection: 'row',
            paddingVertical: 10,
            backgroundColor: '#fff'
        }, styles.borderBottom]}>
        <View style={{
            flexDirection: 'row',
            paddingHorizontal: 10,
            alignItems: 'center',
            flex: 4
        }}>
            <View style={{
                borderWidth: StyleSheet.hairlineWidth,
                borderRadius: 2,
                borderColor: Constant.SEPLINECOLOR,
                padding: 5
            }}>
                <Image style={{width: 50, height: 40}}
                       source={{uri: imageUrl||''}}/>
            </View>
            <View style={{paddingHorizontal: 10}}>
                <View>
                    <Text style={{color: Constant.TEXT_COLOR_3}}>{name}</Text>
                </View>
                <View style={{flexDirection: 'row', alignItems: 'center'}}>
                    <View>
                        <Star
                            count={score}/>
                    </View>
                    <View style={{paddingHorizontal: 10, paddingVertical: 5}}>
                        <Text style={styles.textSmall}>{score}</Text>
                    </View>
                    <View>
                        <Text style={styles.textSmall}>月售{saleMount}</Text>
                    </View>
                </View>
                <View>
                    <Text style={{fontSize: 11, color: Constant.TEXT_COLOR_6}}>{address}</Text>
                </View>
            </View>
        </View>
        <View style={{
            flexDirection: 'row',
            alignItems: 'flex-end',
            justifyContent: 'flex-end',
            flex: 2,
            paddingHorizontal: 10
        }}>
            <Text style={styles.textSmall}>{distance}m</Text>
            <Text style={[styles.textSmall, {paddingHorizontal: 4}]}>|</Text>
            <Text style={styles.textSmall}>{deliveryTime}分钟</Text>
        </View>
    </TouchableOpacity>
}

// 悬浮购物车按钮
const FloatShoppingCart = ({navigation}) => {
    return <View>
        <TouchableOpacity
            onPress={() => {
                navigation.navigate('ShoppingCart')
            }}
            activeOpacity={0.95}
            style={{
                position: 'absolute',
                bottom: 20,
                right: 20
            }}>
            <Image source={require('../../asserts/home/Shopping-Cart.png')}/>
        </TouchableOpacity>
    </View>
}

@observer
export default class Home extends Component {

    // 互联网品牌
    @observable internetBrandList = [];
    // 热销品牌
    @observable hotSalesBrandList = [];
    // 本地品牌
    @observable localBrandList = [];

    @observable nearbyShopList = [];

    @observable isRefreshing = true ;

    @observable scrollY = new Animated.Value(0.0);

    static navigationOptions = {
        header: null
    }

    constructor(props) {
        super(props);
        this.SEARCH_FIX_Y = 50;
        this.SEARCH_BOX_Y = 70;

        // 监听登陆退出事件
        this.subscription = DeviceEventEmitter.addListener(Constant.LOGINOUT, this.login.bind(this));
    }

    renderFixHeader() {
        let showY = this.scrollY.interpolate({
            inputRange: [0,30, this.SEARCH_FIX_Y, this.SEARCH_BOX_Y],
            outputRange: [-9999, -9999, 0, 0]
        })

        return <Animated.View
            style={[styles.header, {
                position: "absolute",
                left: 0,
                right: 0,
                top: 0,
                height: 70,
                transform: [
                    {translateY: showY}
                ]
            }]}>
            <LinearGradient colors={['#14c2fc', '#399cfc']} style={{flex: 1}}/>
            <View style={{
                position: "absolute",
                marginHorizontal: 20,
                backgroundColor: '#fff',
                height: 30,
                alignItems: 'center',
                justifyContent: 'center',
                left: 0,
                right: 0,
                top: 30,
            }}>
                <TouchableOpacity style={{flexDirection: 'row', alignItems: 'center'}}>
                    <View style={{paddingHorizontal: 5}}>
                        <Image source={require('../../asserts/home/Magnifier.png')}/>
                    </View>
                    <Text style={{color: Constant.TEXT_COLOR_6, fontSize: 13}}>输入商家，商品名称</Text>
                </TouchableOpacity>
            </View>
        </Animated.View>

    }

    async componentWillMount() {
        WeChat.registerApp('wx29fb35e25d660f0a');
        // 品牌列表
        this._onRefresh();
        observe(addressMgrStore, 'activeAddress', (change) => {
            // 附近店铺列表
            this.loadShopList(change.newValue.latitude, change.newValue.longitude);
        });
    }

    componentWillUnmount() {
        this.subscription.remove();
    };

    componentDidMount() {
        SplashScreen.hide();
        // 监听登陆退出事件
        this.subscription = DeviceEventEmitter.addListener(Constant.LOGINOUT, this.login.bind(this));
    }

    login() {
        this.props.navigation.navigate('Login');
    }

    // 加载附近的水站列表
    loadShopList(latitude,longitude){
        RequestUtil.requestData('shopList', {
            "latitude": latitude,
            "longtitude":longitude,
            'cityName': '北京'
        }).then((list) => {
            LOG('shopList:' + JSON.stringify(list));
            if (list && list.length) {
                this.nearbyShopList = list;
            }
        })
    }


    _onRefresh(){
        this.fetchBrands();
    }

    render() {
        let headerOpaticy = this.scrollY.interpolate({
            inputRange: [0, this.SEARCH_BOX_Y],
            outputRange: [1, 0]
        })
        return <View style={[styles.flex, {backgroundColor: Constant.GRAYBGCOLOR}]}>
            <ScrollView
                refreshControl={<RefreshControl
                    refreshing={this.isRefreshing}
                    onRefresh={this._onRefresh.bind(this)}
                    tintColor={Constant.TEXT_COLOR_9}
                />}
                iosautomaticallyAdjustContentInsets={false}
                onScroll={
                    Animated.event([{nativeEvent: {contentOffset: {y: this.scrollY}}}])
                }
                scrollEventThrottle={16}>
                <Animated.View style={{opacity: headerOpaticy}}>
                    <Bg/>
                    <Header onClick={() => {
                        this.props.navigation.navigate('DeliveryAddress')
                    }}/>
                    <LastAddress onClick={() => {
                        this.props.navigation.navigate('DeliveryAddress')
                    }}/>
                </Animated.View>
                <Banner/>
                <InternetBrand
                    list={this.internetBrandList}/>
                <HotSalesBrand
                    list={this.hotSalesBrandList}
                    onClick={() => {
                        this.props.navigation.navigate('Brand')
                    }}/>
                <LocalBrand
                    list={this.localBrandList}/>
                <View>
                    <Label title="附近店铺"/>
                    {
                        this.nearbyShopList.map((shop, index) => {
                            return <ShopCell
                                shop={shop}
                                key={index}
                                onClick={() => {
                                    this.props.navigation.navigate('WaterShop', {shop})
                                }}/>
                        })
                    }
                </View>
            </ScrollView>
            {
                this.renderFixHeader()
            }
            <WaterTiketShowModal/>
            <FloatShoppingCart navigation={this.props.navigation}/>
            <Placeholder.ImageContent
                size={60}
                animate="fade"
                lineNumber={4}
                lineSpacing={5}
                lastLineWidth="30%"
                onReady={!this.isRefreshing}
            >
            </Placeholder.ImageContent>
        </View>
    }

    // 获取品牌
    fetchBrands() {
        this.isRefreshing = true ;
        Promise.all([
            RequestUtil.requestData('brand/internet'),// 互联网品牌
            RequestUtil.requestData('brand/hotsale'),// 热卖品牌
            RequestUtil.requestData('brand/localfamouse')// 本地品牌
        ]).then(results => {
            this.isRefreshing = false ;
            if (results instanceof Array) {
                let internet = results[0];
                let hotsale = results[1];
                let localfamouse = results[2];
                if (internet instanceof Array) {
                    this.internetBrandList = internet;
                }
                ;
                if (hotsale instanceof Array) {
                    this.hotSalesBrandList = hotsale;
                }
                ;
                if (localfamouse instanceof Array) {
                    this.localBrandList = localfamouse;
                }
                ;
            }
        })
    }
}


const styles = {
    center: {
        justifyContent: 'center',
        alignItems: 'center'
    },
    flex: {
        flex: 1
    },
    borderBottom: {
        borderBottomColor: Constant.SEPLINECOLOR,
        borderBottomWidth: StyleSheet.hairlineWidth
    },
    textSmall: {
        fontSize: 11,
        color: Constant.TEXT_COLOR_6,
    },
    header: {
        height: 60,
    }
}



